package com.bridge.common.intercepters;

import android.util.Log;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Set;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * 配置http请求日志
 */

public class LoggerIntercepter implements Interceptor {

    private String logMessage = "";

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request originRequest = chain.request();
        logMessageAppendHeader(originRequest);
        RequestBody requestBody = originRequest.body();
        logMessageAppendRequestBody(requestBody);
        /**打印请求**/
        Response response = chain.proceed(originRequest);
        String responseBodyStr = response.body().string();
        /**打印回调**/
        Log.e("dongnao","------request&response--->\n" + logMessage + "responseBody--->\n" + responseBodyStr + "\n");
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), responseBodyStr))
                .build();
    }

    private void logMessageAppendHeader(Request request) throws UnsupportedEncodingException {
        logMessage = "";
        String url = request.url().toString();
        logMessage = logMessage + "request url--->" + URLDecoder.decode(URLDecoder.decode(url, "UTF-8"),
                "UTF-8") + "\n" + url + "\n" + "request " +
                "headers" +
                "\n";
        Headers requestHeaders = request.headers();
        Set<String> names = requestHeaders.names();
        for (String name : names) {
            logMessage = logMessage + requestHeaders.values(name) + "\n";
        }
    }

    private void logMessageAppendRequestBody(RequestBody requestBody) throws IOException {
        if (requestBody == null) {
            return;
        }

        MediaType contentType = requestBody.contentType();
        if (contentType == null) {
            return;
        }
        if (!contentType.toString().contains("application/json")) {
            return;
        }
        Charset charset = Charset.forName("UTF8");
        charset = contentType.charset(charset);

        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);

        String contents = buffer.readString(charset);
        logMessage = logMessage + "encoded requestBody:" + contents + "\n";
        contents = URLDecoder.decode(contents);
        contents = URLDecoder.decode(contents);
        logMessage = logMessage + "decoded requestBody:" + contents + "\n";
    }
}
